import { createStore } from 'vuex'
import router from '@/router/index'

import api from "@/api/index";
import utils from "@/utils/index";

let userInfo = utils.getlocalStorage("userInfo") || {};
const defaultState = {
    count: 0,
    userInfo: userInfo,
    currentUser: userInfo.mockUser || userInfo.user || {}
}

export default createStore({
    state() {
        return defaultState
    },
    mutations: {
        login(state, data) {
            state.userInfo = data
            state.currentUser = data.mockUser || data.user || {}
        },
        logout(state) {
            state.userInfo = {}
            state.currentUser = {}
        }
    },
    actions: {
        async login(context, payload) {
            let { data } = await api.common.login(payload);

            if (data) {
                utils.setlocalStorage("userInfo", data);
                context.commit('login', data)
            }
        },
        async logout(context) {
            let userInfo = utils.getlocalStorage("userInfo") || {};

            api.common.logout({
                sessionid: userInfo.sessionid,
                uid: userInfo.uid,
            });

            utils.removelocalStorage("userInfo");
            utils.removeCookie("sessionid");
            context.commit('logout')
            utils.removelocalStorage("tabs");
            utils.removelocalStorage("activeName");

            setTimeout(() => {
                router.replace({
                    name: 'login'
                })
            }, 0);
        },
    },
    getters: {
        currentUser(state) {
            return state.userInfo.mockUser || (state.userInfo.user || {})
        },
        // mockUser(state) {
        //     return state.userInfo.mockUser
        // }
    }
})